<template>
  <div class="image-check-container">
    <h2>图片访问检查工具</h2>
    
    <div class="section">
      <h3>1. 当前环境信息</h3>
      <div class="info-box">
        <div class="info-row">
          <span class="label">开发环境:</span>
          <span class="value">{{ isDev ? '是' : '否' }}</span>
        </div>
        <div class="info-row">
          <span class="label">穿透环境:</span>
          <span class="value">{{ isTunnel ? '是' : '否' }}</span>
        </div>
        <div class="info-row">
          <span class="label">当前域名:</span>
          <span class="value">{{ currentHost }}</span>
        </div>
        <div class="info-row">
          <span class="label">API基础URL:</span>
          <span class="value">{{ apiBaseUrl }}</span>
        </div>
        <div class="info-row">
          <span class="label">MinIO地址:</span>
          <span class="value">{{ minioEndpoint }}</span>
        </div>
      </div>
    </div>
    
    <div class="section">
      <h3>2. 图片URL测试</h3>
      <van-field
        v-model="testUrl"
        label="图片URL"
        placeholder="输入要测试的图片URL"
        :border="false"
      />
      <div class="button-row">
        <van-button type="primary" @click="testImage">测试图片</van-button>
        <van-button plain @click="clearResults">清空结果</van-button>
      </div>
      
      <div class="result-box" v-if="testResult.originalUrl">
        <h4>测试结果</h4>
        <div class="info-row">
          <span class="label">原始URL:</span>
          <span class="value">{{ testResult.originalUrl }}</span>
        </div>
        <div class="info-row">
          <span class="label">处理后URL:</span>
          <span class="value">{{ testResult.processedUrl }}</span>
        </div>
        <div class="info-row">
          <span class="label">URL类型:</span>
          <span class="value">{{ testResult.type }}</span>
        </div>
        
        <div class="preview-box">
          <div class="preview-item">
            <h5>原始图片</h5>
            <img :src="testResult.originalUrl" @error="handleOriginalError" />
            <div class="status" :class="originalStatus.success ? 'success' : 'error'">
              {{ originalStatus.message }}
            </div>
          </div>
          
          <div class="preview-item">
            <h5>处理后图片</h5>
            <img :src="testResult.processedUrl" @error="handleProcessedError" />
            <div class="status" :class="processedStatus.success ? 'success' : 'error'">
              {{ processedStatus.message }}
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="section">
      <h3>3. 通用处理</h3>
      <p>以下是常见问题的解决方案:</p>
      <ul>
        <li>本地MinIO图片无法在外部访问 - 确保FRP配置正确，端口映射正确</li>
        <li>MinIO图片无法加载 - 使用后端代理功能访问</li>
        <li>头像显示为默认猫咪图片 - 原始URL可能无效</li>
      </ul>
      
      <div class="button-row">
        <van-button type="primary" @click="checkCurrentAvatar">检查当前头像</van-button>
        <van-button type="success" @click="testMinioAccess">测试MinIO</van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { showToast } from 'vant';
import { MINIO_CONFIG } from '../../config/services';
import { processImageUrl } from '../../utils/imageUtils';
import { API_CONFIG } from '../../config/env';
import myAxios from '../../plugins/myAxios';

// 环境信息
const isDev = ref(process.env.NODE_ENV === 'development');
const isTunnel = ref(window.location.host.includes('47.109.146.201'));
const currentHost = ref(window.location.host);
const apiBaseUrl = ref(API_CONFIG.baseURL);
const minioEndpoint = ref(MINIO_CONFIG.getEndpoint());

// 测试数据
const testUrl = ref('');
const testResult = ref({
  originalUrl: '',
  processedUrl: '',
  type: ''
});

// 图片状态
const originalStatus = ref({
  success: false,
  message: ''
});

const processedStatus = ref({
  success: false,
  message: ''
});

// 测试图片
const testImage = () => {
  if (!testUrl.value) {
    showToast('请输入URL');
    return;
  }
  
  // 重置状态
  originalStatus.value = { success: false, message: '加载中...' };
  processedStatus.value = { success: false, message: '加载中...' };
  
  // 设置测试结果
  const processed = processImageUrl(testUrl.value);
  testResult.value = {
    originalUrl: testUrl.value,
    processedUrl: processed,
    type: getUrlType(testUrl.value)
  };
};

// 清空测试结果
const clearResults = () => {
  testResult.value = {
    originalUrl: '',
    processedUrl: '',
    type: ''
  };
  originalStatus.value = { success: false, message: '' };
  processedStatus.value = { success: false, message: '' };
};

// 原始图片错误处理
const handleOriginalError = (_e) => {
  originalStatus.value = {
    success: false,
    message: '无法加载图片'
  };
};

// 处理后图片错误处理
const handleProcessedError = (_e) => {
  processedStatus.value = {
    success: false,
    message: '无法加载图片'
  };
};

// 获取URL类型
const getUrlType = (url) => {
  if (!url) return '空URL';
  if (url.startsWith('data:')) return '数据URL';
  if (url.startsWith('blob:')) return 'Blob URL';
  if (url.startsWith('https://')) return 'HTTPS URL';
  if (url.includes('127.0.0.1') || url.includes('localhost')) return '本地URL';
  if (url.includes(':9090') || url.includes('minio')) return 'MinIO URL';
  return '其他URL';
};

// 检查当前用户头像
const checkCurrentAvatar = async () => {
  try {
    const res = await myAxios.get('/user/current');
    if (res.code === 0 && res.data) {
      testUrl.value = res.data.avatarUrl || '';
      testImage();
    } else {
      showToast('获取当前用户信息失败');
    }
  } catch (error) {
    showToast('请求失败');
    console.error(error);
  }
};

// 测试MinIO访问
const testMinioAccess = async () => {
  try {
    testUrl.value = MINIO_CONFIG.getEndpoint();
    testImage();
    
    const res = await myAxios.post('/image/minio/test');
    if (res.code === 0) {
      showToast(res.data.success ? 'MinIO连接正常' : 'MinIO连接失败');
    } else {
      showToast('MinIO测试失败');
    }
  } catch (error) {
    showToast('测试请求失败');
    console.error(error);
  }
};

// 监听图片加载状态
onMounted(() => {
  const checkInterval = setInterval(() => {
    if (testResult.value.originalUrl) {
      const original = document.querySelector('.preview-item:first-child img') as HTMLImageElement;
      if (original && original.complete) {
        originalStatus.value = {
          success: original.naturalWidth > 0,
          message: original.naturalWidth > 0 ? '加载成功' : '加载失败'
        };
      }
      
      const processed = document.querySelector('.preview-item:last-child img') as HTMLImageElement;
      if (processed && processed.complete) {
        processedStatus.value = {
          success: processed.naturalWidth > 0,
          message: processed.naturalWidth > 0 ? '加载成功' : '加载失败'
        };
      }
    }
  }, 1000);
  
  return () => clearInterval(checkInterval);
});
</script>

<style scoped>
.image-check-container {
  padding: 16px;
  max-width: 800px;
  margin: 0 auto;
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 24px;
}

.section {
  margin-bottom: 30px;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 16px;
}

h3 {
  color: #1989fa;
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 18px;
}

.info-box {
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 12px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
}

.label {
  font-weight: bold;
  width: 120px;
}

.value {
  flex: 1;
  word-break: break-all;
}

.button-row {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  margin-bottom: 16px;
}

.result-box {
  margin-top: 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 16px;
}

.result-box h4 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #333;
}

.preview-box {
  display: flex;
  gap: 16px;
  margin-top: 16px;
  flex-wrap: wrap;
}

.preview-item {
  flex: 1;
  min-width: 200px;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 12px;
  text-align: center;
}

.preview-item h5 {
  margin-top: 0;
  margin-bottom: 12px;
}

.preview-item img {
  max-width: 100%;
  max-height: 200px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.status {
  margin-top: 12px;
  font-weight: bold;
}

.status.success {
  color: green;
}

.status.error {
  color: red;
}

ul {
  padding-left: 20px;
  margin-bottom: 20px;
}

li {
  margin-bottom: 8px;
}
</style> 